<?php

namespace plugin\ycMassage\app\admin\controller;

use app\common\builder\FormBuilder;
use app\common\builder\ListBuilder;
use app\common\service\UploadService;
use plugin\ycMassage\app\BaseController;
use plugin\ycMassage\app\model\MassageCoupon;
use plugin\ycMassage\app\model\MassageCouponCode;
use plugin\ycMassage\app\model\MassageUser;
use plugin\ycMassage\utils\enum\CouponValidType;
use plugin\ycMassage\utils\enum\CouponCodeState;
use think\facade\Db;
use think\Request;

class CouponCodeController extends BaseController
{
    public function issue(Request $request)
    {
        $coupon_id = $request->get('id');
        $MassageCoupon = MassageCoupon::where(['id' => $coupon_id, 'saas_appid' => $request->saas_appid])->find();
        if (!$MassageCoupon) {
            return $this->fail('优惠券不存在');
        }
        if ($request->method() === 'POST') {
            $D = $request->post();
            $D['saas_appid'] = $request->saas_appid;

            $num = 1;
            if (!empty($D['num'])) {
                $num = (int)$D['num'];
                if ($num > 1000) {
                    $num = 1000;
                }
            }
            $startTime = null;
            $endTIme = null;
            switch ($MassageCoupon->valid_type) {
                case CouponValidType::TIME['value']:
                    list($start_time, $end_time) = $MassageCoupon->valid_time;
                    $startTime = $start_time;
                    $endTIme = $end_time;
                    break;
            }
            Db::startTrans();
            try {
                $couponData = [];
                $createCode = [];
                for ($i = 0; $i < $num; $i++) {
                    $code = MassageCouponCode::getCouponCode($MassageCoupon->id);
                    if (in_array($code, $createCode)) {
                        $i--;
                        continue;
                    }
                    $createCode[] = $code;
                    $temp = [
                        'saas_appid' => $request->saas_appid,
                        'coupon_id' => $MassageCoupon->id,
                        'state' => $D['state'],
                        'code' => $code
                    ];
                    if ($startTime) {
                        $temp['start_time'] = $startTime;
                    }
                    if ($endTIme) {
                        $temp['end_time'] = $endTIme;
                    }
                    $couponData[] = $temp;
                }
                if (empty($couponData)) {
                    return $this->fail('创建失败');
                }
                $MassageCoupon->sum = Db::raw('sum+' . $num);
                $MassageCoupon->num = Db::raw('num+' . $num);
                $MassageCoupon->save();
                $MassageCouponCode = new MassageCouponCode;
                $MassageCouponCode->saveAll($couponData);
                Db::commit();
                return $this->success('发行成功');
            } catch (\Throwable $th) {
                Db::rollback();
                return $this->fail('发行失败：' . $th->getMessage());
            }
        }

        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('coupon_id', 'select', '优惠券', $MassageCoupon->id, [
            'col' => 24,
            'props' => [
                'disabled' => true
            ],
            'options' => [
                ['value' => $MassageCoupon->id, 'label' => $MassageCoupon->title]
            ]
        ]);
        $builder->addRow('state', 'radio', '状态', CouponCodeState::YES['value'], [
            'col' => 12,
            'options' => CouponCodeState::getOptions()
        ]);
        $builder->addComponent('num', 'input-number', '发行数量', 100, [
            'col' => 12,
            'props' => [
                'controls' => false,
                'min' => 0,
                'precision' => 0
            ],
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function indexGetTable(Request $request)
    {
        $limit   = $request->get('limit', 20);
        $builder = new ListBuilder;
        $builder->checkboxConfig();
        $builder->addActionOptions('操作', [
            'width' => 160
        ]);
        $builder->pageConfig([
            'pageSize' => $limit
        ]);
        $builder->addBottomButton('deleteAll', '删除', [
            'api'    => $this->pluginPrefix . '/admin/CouponCode/deleteAll',
            'type'      => 'confirm',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除所选数据',
            'type' => 'error',
        ], [
            'type' => 'error',
        ]);
        $builder->addRightButton('bind', '绑定', [
            'api'    => $this->pluginPrefix . '/admin/CouponCode/bind',
            'path' => '/CouponCode/bind',
            'type'      => 'modal',
            'params' => [
                'field' => 'bind',
                'value' => 1
            ]
        ], [], [
            'type' => 'primary',
            'link' => true
        ]);
        $builder->addRightButton('cancel', '作废', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/CouponCode/cancel',
            'method' => 'delete',
            'params' => [
                'field' => 'state',
                'value' => CouponCodeState::YES['value']
            ]
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认作废该数据',
        ], [
            'type' => 'warning',
            'link' => true
        ]);
        $builder->addRightButton('delete', '删除', [
            'type'   => 'confirm',
            'api'    => $this->pluginPrefix . '/admin/CouponCode/delete',
            'method' => 'delete'
        ], [
            'title'   => '温馨提示',
            'content' => '是否确认删除该数据',
        ], [
            'type' => 'danger',
            'link' => true
        ]);
        $builder->addColumn('id', '序号', [
            'width' => 90,
            'type' => 'checkbox'
        ])
            ->addColumn('title', '优惠券', [
                'width' => 120,
            ])
            ->addColumn('code', '券码')
            ->addColumn('start_time', '开始时间', [
                'width' => 120,
            ])
            ->addColumn('end_time', '结束时间', [
                'width' => 120,
            ])
            ->addColumn('receive_time', '领取时间', [
                'width' => 120,
            ])
            ->addColumn('use_time', '使用时间', [
                'width' => 120,
            ])
            ->addColumnEle('headimg', '用户头像', [
                'width' => 60,
                'params' => [
                    'type' => 'image',
                ],
            ])
            ->addColumn('nickname', '用户昵称', [
                'width' => 90,
            ])
            ->addColumn('username', '用户账号', [
                'width' => 90,
            ])
            ->addColumnEle('state', '状态', [
                'width' => 100,
                'params' => [
                    'type'    => 'tags',
                    'options' => CouponCodeState::dictOptions(),
                ],
            ]);
        return $this->successRes($builder->create());
    }
    public function index(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 20);
        $where = [
            ['cc.saas_appid', '=', $request->saas_appid]
        ];
        $data = MassageCouponCode::alias('cc')->where($where)
            ->join('massage_user user', 'user.id=cc.uid', 'left')
            ->join('massage_coupon c', 'c.id=cc.coupon_id', 'left')
            ->order('cc.id desc')
            ->field('cc.*,user.headimg,user.username,user.nickname,c.title')
            ->paginate([
                'list_rows' => $limit,
                'page' => $page
            ])->each(function ($item) {
                $item->bind = 0;
                if ($item->state === CouponCodeState::YES['value'] && !$item->uid) {
                    $item->bind = 1;
                }
                if ($item->nickname) {
                    $item->nickname = base64_decode($item->nickname);
                }
                if (strpos($item->headimg, 'http') !== 0) {
                    $item->headimg = UploadService::url($item->headimg);
                }
            });
        return $this->successRes($data);
    }
    public function bind(Request $request)
    {
        $id = $request->get('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        $MassageCouponCode = MassageCouponCode::where($where)->find();
        if (!$MassageCouponCode) {
            return $this->fail('该优惠券不存在');
        }
        if ($MassageCouponCode->state !== CouponCodeState::YES['value']) {
            return $this->fail('该优惠券不可绑定');
        }
        $MassageCoupon = MassageCoupon::where(['id' => $MassageCouponCode->coupon_id])->find();
        if (!$MassageCoupon) {
            return $this->fail('该优惠券不存在');
        }
        if ($request->method() === 'POST') {
            $uid = $request->post('uid');
            $MassageUser = MassageUser::where(['id' => $uid, 'saas_appid' => $request->saas_appid])->find();
            if (!$MassageUser) {
                return $this->fail('用户不存在');
            }
            try {
                MassageCouponCode::receive($MassageCoupon, $MassageCouponCode, $uid);
                return $this->success('绑定成功');
            } catch (\Throwable $th) {
                return $this->fail($th->getMessage());
            }
        }
        $builder = new FormBuilder;
        $builder->setMethod('POST');
        $builder->addRow('title', 'input', '优惠券', $MassageCoupon->title, [
            'col' => 24,
            'props' => [
                'disabled' => true
            ],
        ]);
        $builder->addRow('uid', 'input', 'UID', '', [
            'col' => 24,
        ]);
        $data = $builder->create();
        return $this->successRes($data);
    }
    public function cancel(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        Db::startTrans();
        try {
            $MassageCouponCode = MassageCouponCode::where($where)->find();
            if (!$MassageCouponCode) {
                throw new \Exception('数据不存在');
            }
            $MassageCoupon = MassageCoupon::where(['id' => $MassageCouponCode->coupon_id])->find();
            if ($MassageCouponCode->state === CouponCodeState::YES['value']) {
                $MassageCoupon->num = Db::raw('num-1');
                $MassageCoupon->save();
            }
            $MassageCouponCode->state = CouponCodeState::EXPIRED['value'];
            $MassageCouponCode->save();
            Db::commit();
            return $this->success('作废成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail('作废失败:' . $th->getMessage());
        }
    }
    public function delete(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', '=', $id]
        ];
        Db::startTrans();
        try {
            $MassageCouponCode = MassageCouponCode::where($where)->find();
            if (!$MassageCouponCode) {
                throw new \Exception('数据不存在');
            }
            $MassageCoupon = MassageCoupon::where(['id' => $MassageCouponCode->coupon_id])->find();
            switch ($MassageCouponCode->state) {
                case CouponCodeState::YES['value']:
                    $MassageCoupon->num = Db::raw('num-1');
                    break;
                case CouponCodeState::NO['value']:
                    $MassageCoupon->use_num = Db::raw('use_num-1');
                    break;
            }
            $MassageCoupon->save();
            $MassageCouponCode->delete();
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail('删除失败');
        }
    }
    public function deleteAll(Request $request)
    {
        $id = $request->post('id');
        $where = [
            ['saas_appid', '=', $request->saas_appid],
            ['id', 'in', $id]
        ];
        Db::startTrans();
        try {
            $MassageCouponCode = MassageCouponCode::where($where)->select();
            if (!$MassageCouponCode) {
                throw new \Exception('数据不存在');
            }
            foreach ($MassageCouponCode as $item) {
                $MassageCoupon = MassageCoupon::where(['id' => $item->coupon_id])->find();
                switch ($item->state) {
                    case CouponCodeState::YES['value']:
                        $MassageCoupon->num = Db::raw('num-1');
                        break;
                    case CouponCodeState::NO['value']:
                        $MassageCoupon->use_num = Db::raw('use_num-1');
                        break;
                }
                $MassageCoupon->save();
                $item->delete();
            }
            Db::commit();
            return $this->success('删除成功');
        } catch (\Throwable $th) {
            Db::rollback();
            return $this->fail('删除失败');
        }
    }
}
